package kr.co.sharping.IO.Data;

import java.util.HashMap;
import java.util.Map;

import kr.co.sharping.Interface.NetworkLoadList;

import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

public class PostListAPI {

	private String url;
	private HashMap<String, String> param;
	private NetworkLoadList mNetworkLoadList;
	
	private Listener<String> listener;
	private ErrorListener errorListener;
	
	private APIRequest request;
	
	public PostListAPI(String url, HashMap<String, String> param) {
		this.url = url;
		this.param = param;
		
		setListener();
		setErrorListener();
		setRequest();
		
	}
	
	public void commit(RequestQueue queue) {
		queue.add(request);
		mNetworkLoadList.onLoadStart();
	}

	public void setRequest() {
		request = new APIRequest(listener, errorListener);
	}
	
	private void setListener() {
		listener = new Listener<String>() {

			@Override
			public void onResponse(String result) {
				mNetworkLoadList.onLoadSuccessEnd(result);
			}
		};
	}
	
	private void setErrorListener() {
		errorListener = new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError err) {
				mNetworkLoadList.onLoadFail(err);
			}
		};
	}
	
	private class APIRequest extends StringRequest {
		
		public APIRequest(Listener<String> listener,
				ErrorListener errorListener) {
			super(Method.POST, url, listener, errorListener);
		}
		
		@Override
		protected Map<String, String> getParams() throws AuthFailureError {
			// TODO Auto-generated method stub
			return param;
		}
	}

	public void setmNetworkLoadList(NetworkLoadList mNetworkLoadList) {
		this.mNetworkLoadList = mNetworkLoadList;
	}
	
}
